<template>
  <div
    style="
      min-height: calc(100vh - 40px);
      width: 297mm;
      margin: 0 auto;
      padding: 20px;
    "
  >
    <div class="header">
      <router-link to="/main/xingzheng/gudingzichan" style=""
        ><button>返回</button></router-link
      >

      <span>
        <button @click="addItem" v-if="!isView">新增申购项</button>
        <button @click="deleteSelectedItems" v-if="!isView">删除选中</button>
        <button @click="saveData" v-if="!isView">保存</button>
        <!-- 添加导出 PDF 按钮 -->
        <button @click="exportToPDF">导出 PDF</button>
        <button>
          <router-link
            style="color: white"
            to="/main/xingzheng/shengoudan/shengoudanList"
            >列表</router-link
          >
        </button>
      </span>
    </div>
    <div class="pdf">
      <h2>申购单</h2>
      <label>NO：</label>
      <input v-model="formData.no" :disabled="isView" />
      <div style="float: left; display: flex; align-items: center">
        <label>申购部门：</label>
        <input v-model="formData.department" :disabled="isView" />&emsp;&emsp;
        <label>日期：</label>
        <input v-model="formData.date" type="date" :disabled="isView" />
      </div>

      <table border="1" style="width: 98%; text-align: center">
        <thead>
          <tr>
            <th class="checkbox">
              <input
                style="width: 20px"
                type="checkbox"
                v-model="isAllChecked"
                @change="toggleAllCheck"
                v-if="!isView"
              />
            </th>
            <th>序号</th>
            <th>品名/规格</th>
            <th>单位</th>
            <th>申购数量</th>
            <th>批准数量</th>
            <th>需用日期</th>
            <th>回复日期</th>
            <th>用途及说明</th>
            <th>备注</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in itemList" :key="index">
            <td class="checkbox">
              <input
                style="width: 20px"
                type="checkbox"
                v-model="item.isChecked"
                @change="updateAllCheckedStatus"
                v-if="!isView"
              />
            </td>
            <td>{{ index + 1 }}</td>
            <td><input v-model="item.productName" :disabled="isView" /></td>
            <td><input v-model="item.unit" :disabled="isView" /></td>
            <td>
              <input
                v-model="item.requestedQuantity"
                type="number"
                :disabled="isView"
              />
            </td>
            <td>
              <input
                v-model="item.approvedQuantity"
                type="number"
                :disabled="isView"
              />
            </td>
            <td>
              <input v-model="item.neededDate" type="date" :disabled="isView" />
            </td>
            <td>
              <input v-model="item.replyDate" type="date" :disabled="isView" />
            </td>
            <td><input v-model="item.purpose" :disabled="isView" /></td>
            <td><input v-model="item.remark" :disabled="isView" /></td>
          </tr>
          <tr>
            <td colspan="10">
              <span style="display: flex; justify-content: space-between">
                <span>
                  <label>核准：</label>
                  <input v-model="formData.approver" :disabled="isView" />
                </span>
                <span>
                  <label>审批：</label>
                  <input v-model="formData.reviewer" :disabled="isView" />
                </span>
                <span>
                  <label>确认：</label>
                  <input v-model="formData.confirmator" :disabled="isView" />
                </span>
                <span>
                  <label>制单：</label>
                  <input v-model="formData.formMaker" :disabled="isView" />
                </span>
              </span>
            </td>
          </tr>
        </tbody>
      </table>

      <p class="vertical-text">
        第一联：存根（白）第二联：计帐（红）第三联：采购（绿）第四联：仓库（黄）
      </p>
    </div>
  </div>
</template>

<script>
import {
  getPurchaseRequestDetail,
  savePurchaseRequest,
} from "@/api/purchaseRequest";
import { Message } from "element-ui";
// 引入 jspdf 和 html2canvas
import jsPDF from "jspdf";
import html2canvas from "html2canvas";

export default {
  data() {
    return {
      pageType: "add", // add, edit, view
      formData: {
        id: null,
        no: this.generateRequestNo(),
        department: "",
        date: this.formatDate(new Date()),
        approver: "",
        reviewer: "",
        confirmator: "",
        formMaker: "",
      },
      itemList: [this.createEmptyItem()],
      isAllChecked: false,
    };
  },
  computed: {
    isView() {
      return this.pageType === "view";
    },
  },
  created() {
    this.initPageData();
  },
  methods: {
    // 初始化页面数据
    async initPageData() {
      const { id, type } = this.$route.query;
      if (type) {
        this.pageType = type;
      }

      if (id) {
        try {
          const response = await getPurchaseRequestDetail(id);
          if (response.data && response.data.code === 200) {
            const detail = response.data.data;
            this.formData = {
              id: detail.id,
              no: detail.no || "",
              department: detail.department || "",
              date: detail.date || "",
              approver: detail.approver || "",
              reviewer: detail.reviewer || "",
              confirmator: detail.confirmator || "",
              formMaker: detail.formMaker || "",
            };

            if (detail.itemList && detail.itemList.length > 0) {
              this.itemList = detail.itemList;
            } else {
              this.itemList = [this.createEmptyItem()];
            }
          } else {
            Message.error(response.data.message || "获取详情失败");
          }
        } catch (error) {
          console.error("获取详情错误：", error);
          Message.error("获取详情失败：" + error.message);
        }
      }
    },

    // 创建空的明细项
    createEmptyItem() {
      return {
        isChecked: false,
        productName: "",
        unit: "",
        requestedQuantity: 0,
        approvedQuantity: 0,
        neededDate: "",
        replyDate: "",
        purpose: "",
        remark: "",
      };
    },

    // 生成申购单编号
    generateRequestNo() {
      const date = new Date();
      const year = date.getFullYear().toString().substr(2);
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      const random = Math.floor(Math.random() * 1000)
        .toString()
        .padStart(3, "0");
      return `SG${year}${month}${day}${random}`;
    },

    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    // 添加明细项
    addItem() {
      this.itemList.push(this.createEmptyItem());
      this.updateAllCheckedStatus();
    },

    // 删除选中的明细项
    deleteSelectedItems() {
      if (this.itemList.filter((item) => item.isChecked).length === 0) {
        Message.warning("请选择要删除的行");
        return;
      }

      this.$confirm("确定要删除所选行吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.itemList = this.itemList.filter((item) => !item.isChecked);
          this.updateAllCheckedStatus();
          Message.success("删除成功");
        })
        .catch(() => {
          // 取消删除
        });
    },

    // 全选/取消全选
    toggleAllCheck() {
      this.itemList.forEach((item) => {
        item.isChecked = this.isAllChecked;
      });
    },

    // 更新全选状态
    updateAllCheckedStatus() {
      this.isAllChecked =
        this.itemList.length > 0 &&
        this.itemList.every((item) => item.isChecked);
    },

    // 验证表单
    validateForm() {
      if (!this.formData.no) {
        Message.error("请填写申购单编号");
        return false;
      }

      if (!this.formData.department) {
        Message.error("请填写申购部门");
        return false;
      }

      if (!this.formData.date) {
        Message.error("请选择申购日期");
        return false;
      }

      if (this.itemList.length === 0) {
        Message.error("请至少添加一项明细");
        return false;
      }

      for (let i = 0; i < this.itemList.length; i++) {
        const item = this.itemList[i];
        if (!item.productName) {
          Message.error(`第${i + 1}行请填写品名/规格`);
          return false;
        }

        if (!item.unit) {
          Message.error(`第${i + 1}行请填写单位`);
          return false;
        }

        if (!item.requestedQuantity || item.requestedQuantity <= 0) {
          Message.error(`第${i + 1}行请填写有效的申购数量`);
          return false;
        }
      }

      return true;
    },

    // 保存数据
    async saveData() {
      if (!this.validateForm()) {
        return;
      }

      try {
        const data = {
          id: this.formData.id,
          no: this.formData.no,
          department: this.formData.department,
          date: this.formData.date,
          approver: this.formData.approver,
          reviewer: this.formData.reviewer,
          confirmator: this.formData.confirmator,
          formMaker: this.formData.formMaker,
          itemList: this.itemList.map((item) => {
            // 移除isChecked属性，后端不需要
            const { isChecked, ...rest } = item;
            return rest;
          }),
        };

        const response = await savePurchaseRequest(data);
        if (response.data && response.data.code === 200) {
          Message.success("保存成功");
          this.$router.push("/main/xingzheng/shengoudan/shengoudanList");
        } else {
          Message.error(response.data.message || "保存失败");
        }
      } catch (error) {
        console.error("保存错误：", error);
        Message.error("保存失败：" + error.message);
      }
    },

    // 导出 PDF 方法
    async exportToPDF() {
      //   try {
      //     const element = document.querySelector(".pdf"); // 假设整个页面内容都在 .container 中
      //     const canvas = await html2canvas(element);
      //     const imgData = canvas.toDataURL("image/png");
      //     const pdf = new jsPDF("landscape");
      //     const imgProps = pdf.getImageProperties(imgData);
      //     const pdfWidth = pdf.internal.pageSize.getWidth();
      //     const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
      //     pdf.addImage(imgData, "PNG", 0, 0, pdfWidth, pdfHeight);
      //     pdf.save("申购单.pdf");
      //   } catch (error) {
      //     console.error("导出 PDF 失败：", error);
      //     Message.error("导出 PDF 失败：" + error.message);
      //   }
      // 创建一个样式元素
      const style = document.createElement("style");
      style.type = "text/css";
      style.media = "print";
      style.textContent = "@page { size: A4 landscape; }";
      // 将样式添加到文档头部
      document.head.appendChild(style);
      // 执行打印
      window.print();
      // 打印完成后移除样式
      document.head.removeChild(style);
    },
  },
};
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
}
table {
  border-collapse: collapse;
  width: 97%;
  margin-top: 10px;
}

th,
td {
  border: 1px solid #000;
  padding: 8px 12px;
}
.pdf {
  /* padding: 20px; */
}
input {
  width: 105px;
  box-sizing: border-box;
  text-align: center;
  border: 0px;
  font-size: 1em;
}

.vertical-text {
  /* font-size: 12px; */
  writing-mode: vertical-rl;
  text-orientation: upright;
  position: absolute;
  right: 0px;
  top: 50%;
  transform: translateY(-50%);
  height: 100%;
}

button {
  margin-right: 10px;
  padding: 5px 10px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #66b1ff;
}
input[type="checkbox"] {
  height: 13px;
}
@media print {
  .checkbox,
  .header {
    display: none;
  }
}
</style>